﻿
function cmsFilePicker_ShowPicker(field, folder) {
    $('#cmsFilePicker').remove();
    var cmsFilePicker = $('<div id="cmsFilePicker" class="cmsFilePicker"><iframe src="/Scripts/IZWebFileManager/FilePicker.aspx?field=' + field + '&folder=' + folder + '" scrolling="no" /></div>');
    cmsFilePicker.prependTo($('#' + field).parents('.cmsModal:first'));
}

function cmsFilePicker_SetPath(field, path) {
    $('#' + field).val(path);
    $('#cmsFilePicker').remove();
}

function cmsGetPageJSON() {
    var draftPage = { Areas: [] };
    $('.contentArea').each(function() {
        var area = {
            Id: $(this).attr('id'),
            Modules: []
        };

        $(this).find('.cmsModule').each(function() {
            if (!$(this).hasClass('cmsInherited') && $(this).data('definition')) {
                var definition = $(this).data('definition');
                definition = $.extend(definition, { ModuleJSON: $.compactJSON($(this).data('config')) });
                area.Modules.push(definition);
            }
        });

        draftPage.Areas.push(area);
    });
    return draftPage;
}

function cmsUpdateModule(moduleElement, params) {
    $(moduleElement).html(cmsLoadingHTML);
    var postParams = { module: $.base64Encode($.compactJSON($(moduleElement).data('config'))), url: window.location.href };
    if (params) {
        postParams = $.extend(postParams, params);
    }
    $.post('/cms/modules/Render/' + $(moduleElement).data('definition').ModuleType, postParams, function(response) {
        // Replace the module content, and refresh the module setup
        $(moduleElement).html(response);
        cmsSetupModule(moduleElement);

        $.get('/CMS/File/ModuleStartupScripts?id=-1', {}, function(modulescripts) {
            try { eval(modulescripts); }
            catch (e) { }
        });
    });
}

// Generic module editor
// Provides basic configuration options when no alternate editor exists
jQuery.fn.cmsModuleEditor = function(opts) {
    return this.each(function() {

        // Cannot edit an inherited module
        if (!$(this).hasClass('cmsInherited')) {

            $(this).dblclick(function(event) {
                var thisRef = this;

                // Ensure that this is the only instance of the editor and make it a modal
                $('#cmsModuleEditor').remove();
                var cmsModuleEditor = $('<div id="cmsModuleEditor" class="cmsModal"></div>');
                cmsModuleEditor
                .appendTo($('body'))
                .show(0)
                .html('<span class="cmsLoadingHTML">' + cmsLoadingHTML + '</span>')
                .modal();

                // Put the dynamically-generated jForm editor for this module type into the div
                cmsModuleEditor.jForm({
                    form: '/cms/modules/GetEditForm/' + $(this).data('definition').ModuleType,
                    object: $(this).data('config'), // Existing config object so that form fields will be populated
                    onCancel: function() {
                        $('#cmsModuleEditor').remove();
                        $.modal.close();
                    },
                    onLoaded: function() {
                        cmsModuleEditor.find('.cmsLoadingHTML').remove();
                        $('<div class="cmsClear"></div>').appendTo($('#cmsModuleEditor'));
                    },
                    onProceed: function(obj) {
                        $('#cmsModuleEditor').remove();
                        $.modal.close();

                        $(thisRef).html(cmsLoadingHTML); // Loading...

                        // Merge the saved config back with the module's config data using $.extend, and save the page
                        $(thisRef).data('config', $.extend($(thisRef).data('config'), obj));
                        cmsSaveDraft();

                        // Get the HTML for the newly-configured module
                        cmsUpdateModule(thisRef);
                    }
                });
            });
        } else {
            // TODO: Unobtrusively inform user why the module edit was not possible
        }
    });
};

var cmsDisablePageVersionCheck = false;

function cmsSaveDraft(callback) {
    cmsDisablePageVersionCheck = true;
    $('#cmsPageVersionLink img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_loading.gif';
    $('#cmsPageVersionLink h3:first').html('Saving Page Draft');
    $('#cmsPageVersionLink h4:first').html('Please wait...');
    var r = false;
    cmsSaveDraft_DoCall(function(response) {
        cmsDisablePageVersionCheck = false;
        cmsPageVersionCheck();
        if (callback) {
            callback(response);
        }
    });
    return r;
}

function cmsSaveDraft_DoCall(callback) {
    $.postJSON('/cms/pages/SaveDraft', { id: cmsPageVersion.json_PageId, pageVersion: $.base64Encode($.compactJSON(cmsPageVersion)), definition: $.base64Encode($.compactJSON(cmsGetPageJSON())) }, function(response) {
        callback(response);
    });
}

function cmsPageVersionCheck() {
    $.postJSON('/cms/pages/GetPageVersion/' + cmsPageVersion.json_PageId, {}, function(pageVersion) {
        cmsPageVersion = pageVersion;
        if (pageVersion.json_IsLive) {
            $('#cmsPageVersionLink img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_page_liveversion.png';
            $('#cmsPageVersionLink h3:first').html('Page Version: Live');
            $('#cmsPageVersionLink h4:first').html('This is what visitors to your site will see.');

            $('#cmsPublish img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_page_liveversion.png';
            $('#cmsPublish h3:first').html('Live');
            $('#cmsPublish h4:first').html('');
            $('#cmsPublish').css('cursor', 'default').addClass('cmsNoHover');
        } else {
            $('#cmsPageVersionLink img:first')[0].src = '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_page_draft.png';
            $('#cmsPageVersionLink h3:first').html('Page Version: Draft');
            $('#cmsPageVersionLink h4:first').html('This is your working draft.  It is not public.');

            $('#cmsPublish h3:first').html('Publish');
            $('#cmsPublish h4:first').html('to Live');
            $('#cmsPublish').css('cursor', 'pointer').removeClass('cmsNoHover');
        }
    });
}

function cmsPageVersionChecker() {
    if (!cmsDisablePageVersionCheck) {
        cmsPageVersionCheck();
    }
    window.setTimeout('cmsPageVersionChecker()', 30000);
}

function cmsSetupModule(moduleDOMElement) {
    var moduleDefinition = $.evalJSON($(moduleDOMElement).find('textarea.cmsModuleDefinition:first').val());
    $(moduleDOMElement).find('textarea.cmsModuleDefinition:first').remove();
    var moduleConfig = $.evalJSON($(moduleDOMElement).find('textarea.cmsModuleConfig:first').val());
    $(moduleDOMElement).find('textarea.cmsModuleConfig:first').remove();

    var additionalConfig = {};
    $(moduleDOMElement).find('textarea.additionalConfig').each(function() {
        additionalConfig = $.extend(additionalConfig, $.evalJSON($(this).val()));
        $(this).remove();
    });

    $(moduleDOMElement).attr('id', moduleDefinition.UniqueID);
    $(moduleDOMElement).data('config', moduleConfig).data('additionalConfig', additionalConfig).data('definition', moduleDefinition);

    if (moduleDefinition.JQueryEditorName.length > 0) {
        if (moduleDefinition.JQueryEditorName.indexOf(',')) {
            $(moduleDefinition.JQueryEditorName.split(',')).each(function(editorIndex, editorName) {
                eval('$(moduleDOMElement).' + $.trim(editorName) + '({});');
            });
        } else {
            eval('$(moduleDOMElement).' + moduleDefinition.JQueryEditorName + '({});');
        }
    }
}
